package org.example.corpus.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.*;
import java.util.List;

public class FileUtil {

    // 获取文件内容
    public static String getFileContent(String filePath) throws IOException {
        String fileExtension = getFileExtension(filePath).toLowerCase();
        StringBuilder content = new StringBuilder();

        switch (fileExtension) {
            case "txt":
                content.append(readTxtFile(filePath));
                break;
            case "pdf":
                content.append(readPdfFile(filePath));
                break;
            case "docx":
                content.append(readDocxFile(filePath));
                break;
            default:
                throw new UnsupportedOperationException("Unsupported file type: " + fileExtension);
        }

        return content.toString();
    }

    // 获取文件扩展名
    private static String getFileExtension(String filePath) {
        int dotIndex = filePath.lastIndexOf(".");
        return (dotIndex == -1) ? "" : filePath.substring(dotIndex + 1);
    }

    // 读取TXT文件
    private static String readTxtFile(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        StringBuilder content = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            content.append(line).append("\n");
        }
        reader.close();
        return content.toString();
    }

    // 读取PDF文件
    private static String readPdfFile(String filePath) throws IOException {
        PDDocument document = PDDocument.load(new File(filePath));
        PDFTextStripper stripper = new PDFTextStripper();
        String content = stripper.getText(document);
        document.close();
        return content;
    }

    // 读取DOCX文件
    private static String readDocxFile(String filePath) throws IOException {
        InputStream inputStream = new FileInputStream(filePath);
        XWPFDocument document = new XWPFDocument(inputStream);
        StringBuilder content = new StringBuilder();

        document.getParagraphs().forEach(paragraph -> content.append(paragraph.getText()).append("\n"));
        inputStream.close();
        return content.toString();
    }
}
